#include "my_stdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

myFILE *mfopen(const char *filename, const char *mode)
{
    int fd = -1; 
    if (strcmp(mode, "r") == 0)
    {
        fd = open(filename, O_RDONLY);

    }
    else if (strcmp(mode, "w") == 0)
    {
        fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);

    }
    else if (strcmp(mode, "a") == 0)
    {
        fd = open(filename,O_WRONLY | O_CREAT | O_APPEND,0666);

    }
    if(fd == -1) return NULL;
    myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
    if(!fp)
    {
        close(fd);
        return NULL;
    }
    fp->fileno = fd;
    fp->flag = FILE_LINE;
    fp->size = 0;
    fp->capacity = SIZE;
    return fp;
}

void mfflush(myFILE *stream)
{
    if(stream->size > 0)
    {
        //进行系统调用刷新,把数据从用户缓存区刷新到内核级缓冲区
        write(stream->fileno,stream->outbuffer,stream->size);
        //刷新完后清空
        stream->size = 0;
    }
}

int mfwrite(const void *ptr, int num, myFILE *stream)
{
    //拷贝
    memcpy(stream->outbuffer+stream->size,ptr,num);
    stream->size+=num;
    //检测是否要刷新
    if(stream->flag == FILE_LINE && stream->size > 0 && stream->outbuffer[stream->size-1] == '\n')
    {
        mfflush(stream);
    }
    return num;
}


void mfclose(myFILE *stream)
{
    if(stream->size>0)
    {
        mfflush(stream);
    }
    close(stream->fileno);
}